package org.openintents.webserver;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;

import org.json.JSONException;
import org.json.JSONObject;
import org.openintents.oiserverdemo.HTMLFileGenerator;
import org.openintents.oiserverdemo.OIServerDemoActivity;

import android.content.ContentProviderClient;
import android.content.ContentValues;
import android.net.Uri;
import android.os.RemoteException;
import android.util.Log;

public class WebServerWrapper extends NanoHTTPD {

	private HTMLFileGenerator generator;
	private InputStream certFile;
	private boolean enableSSL;
	private int SSLPort;
	private String hostname;
	
	public WebServerWrapper(int port, File wwwroot,  boolean enableSSL, InputStream certFile) throws IOException, NoSuchAlgorithmException {
		super(port, wwwroot, certFile);
		this.certFile = certFile;
		this.enableSSL = enableSSL;
		generator = new HTMLFileGenerator(wwwroot);
	}

	public void setSSLPort(int port) {
		SSLPort = port;
	}
	
	public void setHostname(String hostname) {
		this.hostname = hostname;
	}
	
	/* (non-Javadoc)
	 * @see org.openintents.webserver.NanoHTTPD#serve(java.lang.String, java.lang.String, java.util.Properties, java.util.Properties, java.util.Properties)
	 */
	@Override
	public Response serve(String uri, String method, Properties header,
			Properties parms, Properties files) {
		
		/*Log.d("org.openintents.oiserverdemo", "**** "+uri+" ****");
		header.list(new PrintStream(System.out));*/
		

		if(certFile == null && enableSSL == true) { // We have to redirect HTTP to HTTPS
			System.out.println("Redirecting to https://"+hostname+":"+SSLPort);
			return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, HTMLFileGenerator.generateInfoRedirect(
					"OIServerDemo", "Redirecting you to the encrypted page", 5, "https://"+hostname+":"+SSLPort));
		}
		
		if(uri.equalsIgnoreCase("/update")) {
			Uri cmd = Uri.parse(uri);
			String id = parms.getProperty("id");
			String text = parms.getProperty("text");
			text = text.trim();
			
			//System.out.println("id = "+id+"\ntitle="+title+"\ntext="+text);
			
			if(id == null || text == null) {
				return new NanoHTTPD.Response(HTTP_BADREQUEST, MIME_HTML, HTMLFileGenerator.generateInfo("Error", "Bad Request"));
				//return super.serve(uri, method, header, parms, files);
			}
			
			String title = text.split("\\r?\\n")[0]; // First line of text is the title
			
			//System.out.println("id = "+id+"\ntitle="+title+"\ntext="+text);
			
			Uri notesURI = Uri.parse("content://org.openintents.notepad/notes");
			ContentProviderClient provider =  OIServerDemoActivity.mContext.getContentResolver().acquireContentProviderClient(notesURI);
			
			ContentValues values = new ContentValues();
			values.put("TITLE", title);
			values.put("NOTE", text);
			
			notesURI = Uri.withAppendedPath(notesURI, "/"+id);
			try {
				provider.update(notesURI, values, null, null);
			} catch (RemoteException e) {
				e.printStackTrace();
				return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, HTMLFileGenerator.generateInfo("Error", e.getMessage()));
			}
			
			/*try {
				generator.generateFiles(OIServerDemoActivity.notesCursor);
			} catch (IOException e) {
				e.printStackTrace();
			}*/
			
			return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, HTMLFileGenerator.generateInfoRedirect("Updated", "Note saved", 5, "oinotepad.html"));
		}
		
		/*OIServerDemoActivity.notesCursor.moveToFirst();
		
		while(OIServerDemoActivity.notesCursor.moveToNext()) {
			OIServerDemoActivity.notesCursor.
		}*/
		
		return super.serve(uri, method, header, parms, files);
	}

	/* (non-Javadoc)
	 * @see org.openintents.webserver.NanoHTTPD#stop()
	 */
	@Override
	public void stop() {
		super.stop();
	}
	
	private String returnJSON(int id, int error, String msg) {
		
		JSONObject object = new JSONObject();
		try {
			object.put("error", error);
			object.put("msg", msg);
			object.put("id", id);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		
		Log.d("tag", object.toString());
		return object.toString();
	}
}
